<?php
/*
 * 地区处理
 * @package    system
 * @author     Mark
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: 860db81f2ab55bdd26c366a99eb8666beff4b504 $
 */
defined('IN_IXDCW') or exit('Access Denied');
/**
 * 区域类管理
 */
class AreaModule extends BasicModule {

	/** @var int 地区id */
	private $_areaid;

	/** @var array|int|String 区域 */
	private $_area = array();

	/** @var string 区域操作的数据表 */
	private $_table;

	/**
	 * constructor
	 * @param int $areaid
	 */
	function __construct($areaid = 0) {
		global $AREA;
		parent::__construct();
		if (!$AREA) $AREA = PCache::read('area.php');
		$this->_areaid = $areaid;
		$this->_area   = $AREA;
		$this->_table  = Table::name(Table::NAME_AREA);
	}

	public function getTable() {
		return $this->_table;
	}

	/**
	 * 添加地区, 更新父子关系
	 * @param $area
	 * @return bool
	 */
	function add($area) {
		if (!is_array($area)) return false;
		$this->_db->query(Sql::insert($this->_table, $area));
		$this->_areaid = $this->_db->insertId();
		if ($area['parentid']) {
			$area['areaid']              = $this->_areaid;
			$this->_area[$this->_areaid] = $area;
			$arrparentid                 = $this->get_arrparentid($this->_areaid, $this->_area);
		} else {
			$arrparentid = 0;
		}
		$this->_db->query("UPDATE {$this->_table} SET arrchildid='$this->_areaid',listorder=$this->_areaid,arrparentid='$arrparentid' WHERE areaid=$this->_areaid");
		return true;
	}

	/**
	 * 删除地区id
	 * @param $areaids
	 * @return bool
	 */
	function delete($areaids) {
		if (is_array($areaids)) {
			foreach ($areaids as $areaid) {
				if (isset($this->_area[$areaid])) {
					$arrchildid = $this->_area[$areaid]['arrchildid'];
					$this->_db->query("DELETE FROM {$this->_table} WHERE areaid IN ($arrchildid)");
				}
			}
		} else {
			$areaid = $areaids;
			if (isset($this->_area[$areaid])) {
				$arrchildid = $this->_area[$areaid]['arrchildid'];
				$this->_db->query("DELETE FROM {$this->_table} WHERE areaid IN ($arrchildid)");
			}
		}
		$this->repair();
		return true;
	}

	/**
	 * 更新名称
	 * @param $area
	 * @return bool
	 */
	function update($area) {
		if (!is_array($area)) return false;
		foreach ($area as $k => $v) {
			if (!$v['areaname']) continue;
			$v['parentid'] = intval($v['parentid']);
			if ($k == $v['parentid']) continue;
			if ($v['parentid'] > 0 && !isset($this->_area[$v['parentid']])) continue;
			$v['listorder'] = intval($v['listorder']);
			$this->_db->query("UPDATE {$this->_table} SET areaname='$v[areaname]',parentid='$v[parentid]',listorder='$v[listorder]' WHERE areaid=$k");
		}
		PCache::sysArea();
		return true;
	}

	/**
	 * 更新区域关联并且生成缓存文件
	 * @return bool
	 */
	function repair() {
		$query = $this->_db->query("SELECT * FROM {$this->_table} ORDER BY listorder,areaid");
		$AREA  = array();
		while ($r = $this->_db->fetchArray($query)) {
			$AREA[$r['areaid']] = $r;
		}
		$childs = array();
		foreach ($AREA as $areaid => $area) {
			$arrparentid = $this->get_arrparentid($areaid, $AREA);
			$this->_db->query("UPDATE {$this->_table} SET arrparentid='$arrparentid' WHERE areaid=$areaid");
			if ($arrparentid) {
				$arr = explode(',', $arrparentid);
				foreach ($arr as $a) {
					if ($a == 0) continue;
					isset($childs[$a]) or $childs[$a] = '';
					$childs[$a] .= ',' . $areaid;
				}
			}
		}
		foreach ($AREA as $areaid => $area) {
			if (isset($childs[$areaid])) {
				$arrchildid = $areaid . $childs[$areaid];
				$this->_db->query("UPDATE {$this->_table} SET arrchildid='$arrchildid',child=1 WHERE areaid='$areaid'");
			} else {
				$this->_db->query("UPDATE {$this->_table} SET arrchildid='$areaid',child=0 WHERE areaid='$areaid'");
			}
		}
		PCache::sysArea();
		return true;
	}

	/**
	 * 获取父级元素所有id
	 * @param $areaid
	 * @param $AREA
	 * @return string
	 */
	function get_arrparentid($areaid, $AREA) {
		if ($AREA[$areaid]['parentid'] && $AREA[$areaid]['parentid'] != $areaid) {
			$parents = array();
			$aid     = $areaid;
			while ($areaid) {
				if ($AREA[$aid]['parentid']) {
					$parents[] = $aid = $AREA[$aid]['parentid'];
				} else {
					break;
				}
			}
			$parents[] = 0;
			return implode(',', array_reverse($parents));
		} else {
			return '0';
		}
	}

	/**
	 * 获取子元素id
	 * @param $areaid
	 * @param $AREA
	 * @return string
	 */
	function get_arrchildid($areaid, $AREA) {
		$arrchildid = '';
		foreach ($AREA as $area) {
			if (strpos(',' . $area['arrparentid'] . ',', ',' . $areaid . ',') !== false) $arrchildid .= ',' . $area['areaid'];
		}
		return $arrchildid ? $areaid . $arrchildid : $areaid;
	}

	/**
	 * code
	 * @param $parentid
	 * @return bool
	 */
	public function code($parentid) {
		if (!$parentid) {
			$parentid = 0;
		}
		$sql   = "select areaid, child from $this->_table where parentid = $parentid order by areaid DESC";
		$areas = $this->_db->getAll($sql);
		foreach ($areas as $k => $area) {
			if ($area['child']) {
				$this->code($area['areaid']);
			}
			$sql = "update $this->_table set single = '" . sprintf("%02d", $k + 1) . "' where areaid={$area['areaid']}";
			$this->_db->query($sql);
		}
		return true;
	}

	public function fullCode($length = 8) {
		foreach ($this->_area as $areaid => $area) {
			$parentids = explode(',', $area['arrparentid']);
			array_shift($parentids);
			array_shift($parentids);
			array_push($parentids, $areaid);
			$fullCode = '';
			foreach ($parentids as $p) {
				$fullCode .= $this->_area[$p]['single'];
			}
			$fullCode = str_pad($fullCode, $length, '0', STR_PAD_RIGHT);
			if ($length == 8) {
				$sql = "update $this->_table set fullcode = '$fullCode' where areaid={$area['areaid']}";
				$this->_db->query($sql);
			}
		}
	}

	public function areaJs($level = 0, $parentid = 0) {
		$lv     = array('c', 't', 'v');
		$letter = $lv[$level];
		foreach ($this->_area as $areaid => $area) {
			if ($area['parentid'] == $parentid) {
				$this->areaJs($level + 1, $areaid);
			}
		}
	}

	public function getChildrenJs($parentid, $level = 0) {
		$lv     = array('c', 't', 'v');
		$letter = $lv[$level];
		$arr = array();
		foreach ($this->_area as $area) {
			if ($area['parentid'] == $parentid) {
				$code = $area['fullcode'];
				$tmp = array(
					'n'  => $area['areaname'],
					'id' => $area['areaid']
				);
				if ($area['child']) {
					$tmp[$letter] = $this->getChildrenJs($area['areaid'], $level + 1);
					$tmp['l'] = count($tmp[$letter]);
				} else {
					$tmp['l'] = 0;
				}
				$arr[$code] = $tmp;
			}
		}
		return $arr;
	}

}